#include "AssetPool.h"
#include "../core/src/AssetManager.h"
#include "AssetModel.h"
#include "QuestionAdder.h"
#include "AttributeAdder.h"
#include "ResponseAdder.h"
#include "ResultAdder.h"
#include "AssetSelector.h"
#include "AssetDelegate.h"
//#include "../core/AssetModel.h"

namespace Xps
{

	AssetPool::AssetPool(XpsAssets::AssetManager* am, QWidget* parent) : QSplitter (parent)
	{
		this->am = am;
		QVBoxLayout* layout = new QVBoxLayout();

		// setup editor container
		editor = new QFrame();
		editor->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
		editor->hide();
		editor->setLayout(new QGridLayout());
		editor->layout()->setMargin(0);

		// create toolbar (will be used by mainwindow)
		tb = new QToolBar("Asset Tools");
		tv = new QTreeView();

		// setup model for treeview (main asset data model for xps)
		tm = new AssetModel(am);
		// init default tree view items (group root items)
		tm->init();

		// setup visual stuff
		tb->setIconSize(QSize(30,30));
		tv->setIconSize(QSize(20,20));
		tv->header()->hide();
		tv->header()->setResizeMode(QHeaderView::Stretch);
		tv->setModel(tm);
		tv->setStyleSheet(	"QTreeView::item::selected { background: #EEEEEE; color: black; }"
							"QTreeView::item::hover { background: #EEEEEE; color: black; }"		);
		tv->header()->resizeSections(QHeaderView::Custom);
		
		// setup asset pool layout
		setLayout(layout);
		addWidget(tv);
		addWidget(editor);
		setStretchFactor(0,90);
		setStretchFactor(1,10);
		setChildrenCollapsible(false);
		setOrientation(Qt::Orientation::Vertical);
		
		// get selection model for context related actions
		selection = tv->selectionModel();
		
		// setup actions and connect them to slot
		initActions();
		
		
		// assign delegate to asset pool tree view
		AssetDelegate* qd = new AssetDelegate(am, editor);
		tv->setItemDelegate(qd);
	}

	void AssetPool::initActions()
	{
		aCreateResult = new QAction(QIcon(":/rs/images/result.png"),"Create Result", this);
		aCreateQuestion = new QAction(QIcon(":/rs/images/question.png"), "Create Question", this);
		aDeleteQuestion = new QAction(QIcon(":/rs/images/question.png"), "Delete Question", this);
		aCreateAttribute = new QAction(QIcon(":/rs/images/attribute.png"),"Create Attribute", this);
		aCreateResponse = new QAction(QIcon(":/rs/images/response.png"),"Create Response", this);
		aAddToTree = new QAction(QIcon(":/rs/images/questionitem.png"),"Create Tree Item", this);
		aCreateResponseAttribute = new QAction(QIcon(":/rs/images/attribute_ref.png"),"Add Attribute", this);

		aCreateResult->setToolTip("Create Result");
		aCreateQuestion->setToolTip("Create Question");
		aCreateAttribute->setToolTip("Create Attribute");
		aCreateResponse->setToolTip("Create Response");
		aDeleteQuestion->setToolTip("Delete Question");

		create_actions.append(aCreateQuestion);
		create_actions.append(aCreateResponse);		
		create_actions.append(aCreateAttribute);
		create_actions.append(aCreateResult);

		delete_actions.append(aDeleteQuestion);

		aDeleteSelected = new QAction(QIcon(":/rs/images/delete.png"),"Delete", this);
		

		tb->addActions(create_actions);
				
		
		// connet actions to asset manager or proxy slot
		connect(aCreateResponseAttribute, SIGNAL(triggered()), this, SLOT(createResponseAttribute()));
		connect(aCreateQuestion, SIGNAL(triggered()), this, SLOT(createQuestion()));
		connect(aCreateAttribute, SIGNAL(triggered()), this, SLOT(createAttribute()));
		connect(aCreateResult, SIGNAL(triggered()), this, SLOT(createResult()));
		connect(aCreateResponse, SIGNAL(triggered()), this, SLOT(createResponse()));
		connect(aDeleteQuestion, SIGNAL(triggered()), this, SLOT(deleteQuestion()));
		connect(aDeleteSelected, SIGNAL(triggered()), this, SLOT(deleteSelected()));
		connect(aAddToTree, SIGNAL(triggered()), this, SLOT(createTreeItem()));
		
	}

	AssetPool::~AssetPool(void)
	{
	}

	void AssetPool::createTreeItem()
	{
		if (selection->currentIndex().isValid() &&
			selection->selection().indexes().count() == 1)
		{

			TreeItem* t = (TreeItem*) tm->itemFromIndex(selection->currentIndex());

			if (t->getType() == QUESTION)
			{
				emit sAddToTree(t->getID());
				return;
			}
		}

		AssetSelector* as = new AssetSelector(this, "Select Question", ":/rs/images/select.png", tm->qm);
		
		if (QDialog::Accepted == as->exec())
		{
			int id = as->selectedAsset();
			
			if (id == -1)
				return;

			emit sAddToTree(id);
		}
	}

	void AssetPool::createQuestion()
	{
		QuestionAdder* qa = new QuestionAdder(this);
		qa->show();
	}

	void AssetPool::createAttribute()
	{
		AttributeAdder* aa = new AttributeAdder(this);
		aa->show();
	}
	void AssetPool::createResult()
	{
		ResultAdder* ra = new ResultAdder(this);
		ra->exec();
	}

	void AssetPool::createResponse()
	{
		if (selection->currentIndex().isValid() &&
			selection->selection().indexes().count() == 1)
		{

			TreeItem* t = (TreeItem*) tm->itemFromIndex(selection->currentIndex());

			if (t->getType() == QUESTION)
			{
				ResponseAdder* aa = new ResponseAdder(t->getID(), this);
				aa->exec();

				return;
			}
		}
		
		AssetSelector* as = new AssetSelector(this, "Select Question", ":/rs/images/select.png", tm->qm);
		
		if (QDialog::Accepted == as->exec())
		{
			int id = as->selectedAsset();
			
			if (id == -1)
				return;

			ResponseAdder* aa = new ResponseAdder(id, this);
			aa->exec();
		}
	}

	void AssetPool::createResponseAttribute()
	{
		AssetSelector* as = new AssetSelector(this, "Select Attribute", ":/rs/images/select.png",tm->attributesModel);

		if (QDialog::Accepted == as->exec())
		{
			int id = as->selectedAsset();
			
			if (id == -1)
				return;


			
			if (selection->currentIndex().isValid() && selection->selection().indexes().count() != 1)
				return;

			QModelIndex respindex = selection->currentIndex();
			TreeItem* ri = (TreeItem*) tm->itemFromIndex(respindex);

			am->createResponseAttribute(ri->data(Qt::UserRole).toInt(), id);
		}
	}

	void AssetPool::deleteSelected()
	{
		if (!selection->currentIndex().isValid())
		 return;
			
		TreeItem* t = (TreeItem*) tm->itemFromIndex(selection->currentIndex());

		if (t->getType() == QUESTION)
			am->deleteQuestion(t->getID());

		if (t->getType() == RESULT)
			am->deleteResult(t->getID());

		if (t->getType() == ATTRIBUTE)
			am->deleteAttribute(t->getID());

		if (t->getType() == RESPONSE)
			am->deleteResponse(((TreeItem*) t->parent())->getID(), t->getID());

		if (t->getType() == RESPONSE_ATTRIBUTE)
			am->deleteResponseAttribute(((TreeItem*) t->parent())->getID(), t->getID());
	}

	void AssetPool::deleteQuestion()
	{
		if (!selection->currentIndex().isValid())
		 return;
			
		TreeItem* t = (TreeItem*) tm->itemFromIndex(selection->currentIndex());

		if (t->getType() == 1)
			am->deleteQuestion(t->getID());
	}

	void AssetPool::contextMenuEvent(QContextMenuEvent * event )
	{
		QMenu* menu = new QMenu();
		generateSpecificMenu(menu);
		menu->exec(event->globalPos());
	}

	void AssetPool::generateSpecificMenu(QMenu* menu)
	{
		if (selection->selection().indexes().count() < 1)
			return;

		TreeItem* t = (TreeItem*) tm->itemFromIndex(selection->currentIndex());

		if (t->getType() == QUESTION)
		{
			menu->addAction(aCreateResponse);
			menu->addAction(aAddToTree);
		}

		if (t->getType() == RESPONSE)
		{
			menu->addAction(aCreateResponseAttribute);
		}

		if (t->getType() == ATTRIBUTES_ROOT)
		{
			menu->addAction(aCreateAttribute);
		}

		if (t->getType() == QUESTIONS_ROOT)
		{
			menu->addAction(aCreateQuestion);
		}

		if (t->getType() == RESULTS_ROOT)
		{
			menu->addAction(aCreateResult);
		}
		
		if (t->getType() != ATTRIBUTES_ROOT &&
			t->getType() != RESULTS_ROOT &&
			t->getType() != QUESTIONS_ROOT)
			menu->addAction(aDeleteSelected);
	}
}